Micron Document
<!DOCTYPE html>
<html class="client-nojs vector-feature-night-mode-disabled vector-feature-language-in-header-enabled vector-feature-language-in-main-page-header-disabled vector-feature-page-tools-pinned-disabled vector-feature-toc-pinned-clientpref-1 vector-feature-main-menu-pinned-disabled vector-feature-limited-width-clientpref-1 vector-feature-limited-width-content-enabled vector-feature-custom-font-size-clientpref-1 vector-feature-appearance-pinned-clientpref-1 vector-sticky-header-enabled" lang="en" dir="ltr"><head>
<meta charset="UTF-8">
<title>Dispose pattern</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="canonical" href="https://en.wikipedia.org/wiki/Dispose_pattern"> <link href="./mw/ext.cite.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/ext.pygments.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.icons.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.search.codex.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/skins.vector.styles.css" rel="stylesheet" type="text/css">
<link href="./mw/user.styles.css" rel="stylesheet" type="text/css">
<meta name="ResourceLoaderDynamicStyles" content="">
<link rel="stylesheet" type="text/css" href="./mw/site.styles.css">
<link rel="stylesheet" type="text/css" href="./mw/noscript.css">
<link rel="stylesheet" type="text/css" href="./footer.css">
<link rel="stylesheet" type="text/css" href="./vector-2022.css">
</head>
<body class="skin--responsive skin-vector skin-vector-search-vue mediawiki ltr sitedir-ltr mw-hide-empty-elt ns-0 ns-subject page-Dispose_pattern rootpage-Dispose_pattern skin-vector-2022 action-view">
<div class="mw-page-container">
<div class="mw-page-container-inner">
<div class="mw-content-container">
<main id="content" class="mw-body">
<header class="mw-body-header vector-page-titlebar">
<h1 id="firstHeading" class="firstHeading mw-first-heading">
<span id="openzim-page-title" class="mw-page-title-main"><span class="mw-page-title-main">Dispose pattern</span></span>
</h1>
</header>
<a id="top"></a>
<div id="bodyContent" class="vector-body ve-init-mw-desktopArticleTarget-targetContainer" aria-labelledby="firstHeading" data-mw-ve-target-container="">
<div id="mw-content-text" class="mw-body-content mw-content-ltr" lang="en" dir="ltr"><div class="mw-content-ltr mw-parser-output" lang="en" dir="ltr">
<style data-mw-deduplicate="TemplateStyles:r1236090951">
/* start https://en.wikipedia.org/ */


.mw-parser-output .hatnote{font-style:italic}.mw-parser-output div.hatnote{padding-left:1.6em;margin-bottom:0.5em}.mw-parser-output .hatnote i{font-style:normal}.mw-parser-output .hatnote+link+.hatnote{margin-top:-0.5em}@media print{body.ns-0 .mw-parser-output .hatnote{display:none!important}}


/* end https://en.wikipedia.org/ */
</style><div role="note" class="hatnote navigation-not-searchable">"Dispose" redirects here. For the music album, see <a href="Dispose_(album)" title="Dispose (album)">Dispose (album)</a>. For other uses, see <a href="Disposal_(disambiguation)" class="mw-redirect mw-disambig" title="Disposal (disambiguation)">Disposal (disambiguation)</a>.</div>
<style data-mw-deduplicate="TemplateStyles:r1251242444">
/* start https://en.wikipedia.org/ */


.mw-parser-output .ambox{border:1px solid #a2a9b1;border-left:10px solid #36c;background-color:#fbfbfb;box-sizing:border-box}.mw-parser-output .ambox+link+.ambox,.mw-parser-output .ambox+link+style+.ambox,.mw-parser-output .ambox+link+link+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+style+.ambox,.mw-parser-output .ambox+.mw-empty-elt+link+link+.ambox{margin-top:-1px}html body.mediawiki .mw-parser-output .ambox.mbox-small-left{margin:4px 1em 4px 0;overflow:hidden;width:238px;border-collapse:collapse;font-size:88%;line-height:1.25em}.mw-parser-output .ambox-speedy{border-left:10px solid #b32424;background-color:#fee7e6}.mw-parser-output .ambox-delete{border-left:10px solid #b32424}.mw-parser-output .ambox-content{border-left:10px solid #f28500}.mw-parser-output .ambox-style{border-left:10px solid #fc3}.mw-parser-output .ambox-move{border-left:10px solid #9932cc}.mw-parser-output .ambox-protection{border-left:10px solid #a2a9b1}.mw-parser-output .ambox .mbox-text{border:none;padding:0.25em 0.5em;width:100%}.mw-parser-output .ambox .mbox-image{border:none;padding:2px 0 2px 0.5em;text-align:center}.mw-parser-output .ambox .mbox-imageright{border:none;padding:2px 0.5em 2px 0;text-align:center}.mw-parser-output .ambox .mbox-empty-cell{border:none;padding:0;width:1px}.mw-parser-output .ambox .mbox-image-div{width:52px}@media(min-width:720px){.mw-parser-output .ambox{margin:0 10%}}@media print{body.ns-0 .mw-parser-output .ambox{display:none!important}}


/* end https://en.wikipedia.org/ */
</style>
<p>In <a href="Object-oriented_programming" title="Object-oriented programming">object-oriented programming</a>, the <b>dispose pattern</b> is a <a href="Design_pattern_(computer_science)" class="mw-redirect" title="Design pattern (computer science)">design pattern</a> for <a href="Resource_management_(computing)" title="Resource management (computing)">resource management</a>. In this pattern, a <a href="System_resource" title="System resource">resource</a> is held by an <a href="Object_(computing)" class="mw-redirect" title="Object (computing)">object</a>, and released by calling a conventional <a href="Method_(computer_science)" class="mw-redirect" title="Method (computer science)">method</a> – usually called <code>close</code>, <code>dispose</code>, <code>free</code>, <code>release</code> depending on the language – which releases any resources the object is holding onto. Many <a href="Programming_language" title="Programming language">programming languages</a> offer <a href="Language_construct" title="Language construct">language constructs</a> to avoid having to call the dispose method explicitly in common situations.
</p><p>The dispose pattern is primarily used in languages whose <a href="Runtime_environment" class="mw-redirect" title="Runtime environment">runtime environment</a> have <a href="Automatic_garbage_collection" class="mw-redirect" title="Automatic garbage collection">automatic garbage collection</a> (see motivation below).
</p>
<meta property="mw:PageProp/toc">
<div class="mw-heading mw-heading2"><h2 id="Motivation">Motivation</h2></div>
<div class="mw-heading mw-heading3"><h3 id="Wrapping_resources_in_objects">Wrapping resources in objects</h3></div>
<p>Wrapping resources in objects is the object-oriented form of <a href="Encapsulation_(computer_programming)" title="Encapsulation (computer programming)">encapsulation</a>, and underlies the dispose pattern.
</p><p>Resources are typically represented by <a href="Handle_(computing)" title="Handle (computing)">handles</a> (abstract references), concretely usually integers, which are used to communicate with an external system that provides the resource. For example, files are provided by the <a href="Operating_system" title="Operating system">operating system</a> (specifically the <a href="File_system" title="File system">file system</a>), which in many systems represents open files with a <a href="File_descriptor" title="File descriptor">file descriptor</a> (an integer representing the file).
</p><p>These handles can be used directly, by storing the value in a variable and passing it as an argument to functions that use the resource. However, it is frequently useful to abstract from the handle itself (for example, if different operating systems represent files differently), and to store additional auxiliary data with the handle, so handles can be stored as a field in a <a href="Record_(computer_science)" title="Record (computer science)">record</a>, along with other data; if this in an <a href="Opaque_data_type" title="Opaque data type">opaque data type</a>, then this provides <a href="Information_hiding" title="Information hiding">information hiding</a> and the user is abstracted from the actual representation.
</p><p>For example, in <a href="C_file_input/output" title="C file input/output">C file input/output</a>, files are represented by objects of the <code>FILE</code> type (confusingly called "<a href="File_handle" class="mw-redirect" title="File handle">file handles</a>": these are a language-level abstraction), which stores an (operating system) handle to the file (such as a <a href="File_descriptor" title="File descriptor">file descriptor</a>), together with auxiliary information like I/O mode (reading, writing) and position in the stream. These objects are created by calling <code><a href="C_file_input/output#fopen" title="C file input/output">fopen</a></code> (in object-oriented terms, a <a href="Constructor_(object-oriented_programming)" title="Constructor (object-oriented programming)">constructor</a>), which acquires the resource and returns a pointer to it; the resource is released by calling <code><a href="C_file_input/output#fclose" title="C file input/output">fclose</a></code> on a pointer to the <code>FILE</code> object.<sup id="cite_ref-1" class="reference"><a href="#cite_note-1"><span class="cite-bracket">[</span>1<span class="cite-bracket">]</span></a></sup> In code:
</p>
<div class="mw-highlight mw-highlight-lang-c mw-content-ltr" dir="ltr"><pre><span class="kt">FILE</span><span class="w"> </span><span class="o">*</span><span class="n">f</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">fopen</span><span class="p">(</span><span class="n">filename</span><span class="p">,</span><span class="w"> </span><span class="n">mode</span><span class="p">);</span>
<span class="c1">// Do something with f.</span>
<span class="n">fclose</span><span class="p">(</span><span class="n">f</span><span class="p">);</span>
</pre></div>
<p>Note that <code>fclose</code> is a function with a <code>FILE *</code> parameter. In object-oriented programming, this is instead an <a href="Instance_method" class="mw-redirect" title="Instance method">instance method</a> on a file object, as in Python:
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
<span class="c1"># Do something with f.</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
<p>This is precisely the dispose pattern, and only differs in syntax and code structure<sup id="cite_ref-2" class="reference"><a href="#cite_note-2"><span class="cite-bracket">[</span>a<span class="cite-bracket">]</span></a></sup> from traditional file opening and closing. Other resources can be managed in exactly the same way: being acquired in a constructor or factory, and released by an explicit <code>close</code> or <code>dispose</code> method.
</p>
<div class="mw-heading mw-heading3"><h3 id="Prompt_release">Prompt release</h3></div>
<p>The fundamental problem that freeing resources aims to solve is that resources are expensive (for example, there may be a limit on the number of open files), and thus should be released promptly. Further, some finalization work is sometimes needed, particularly for I/O, such as flushing buffers to ensure that all data is actually written.
</p><p>If a resource is unlimited or effectively unlimited, and no explicit finalization is necessary, it is not important to release it, and in fact short-lived programs often do not explicitly release resources: due to short run time, they are unlikely to exhaust resources, and they rely on the <a href="Runtime_system" title="Runtime system">runtime system</a> or <a href="Operating_system" title="Operating system">operating system</a> to do any finalization.
</p><p>However, in general resources must be managed (particularly for long-lived programs, programs that use many resources, or for safety, to ensure that data is written out). Explicit disposal means that resource finalization and release is deterministic and prompt: the <code>dispose</code> method does not complete until these are done.
</p><p>An alternative to requiring explicit disposal is to tie resource management to <a href="Object_lifetime" title="Object lifetime">object lifetime</a>: resources are acquired during <a href="Object_creation" class="mw-redirect" title="Object creation">object creation</a>, and released during <a href="Object_destruction" class="mw-redirect" title="Object destruction">object destruction</a>. This approach is known as the <a href="Resource_Acquisition_Is_Initialization" class="mw-redirect" title="Resource Acquisition Is Initialization">Resource Acquisition Is Initialization</a> (RAII) idiom, and is used in languages with deterministic memory management (e.g. <a href="C%2B%2B" title="C++">C++</a>). In this case, in the example above, the resource is acquired when the file object is created, and when the scope of the variable <code>f</code> is exited, the file object that <code>f</code> refers to is destroyed, and as part of this, the resource is released.
</p><p>RAII relies on object lifetime being deterministic; however, with automatic memory management, <a href="Object_lifetime" title="Object lifetime">object lifetime</a> is not a concern of the programmer: objects are destroyed at some point after they are no longer used, but <i>when</i> is abstracted. Indeed, lifetime is often not deterministic, though it may be, notably if <a href="Reference_counting" title="Reference counting">reference counting</a> is used. Indeed, in some cases there is no guarantee that objects will <i>ever</i> be finalized: when the program terminates, it may not finalize the objects, and instead just let the operating system reclaim memory; if finalization is required (e.g., to flush buffers), data loss can occur.
</p><p>Thus by not coupling resource management to object lifetime, the dispose pattern allows <i>resources</i> to be released promptly, while giving implementation flexibility for memory management. The cost of this is that resources must be managed manually, which can be tedious and error-prone.
</p>
<div class="mw-heading mw-heading2"><h2 id="Early_exit">Early exit</h2></div>
<p>A key problem with the dispose pattern is that if the <code>dispose</code> method is not called, the resource is leaked. A common cause of this is early exit from a function, due to an early return or exception.
</p><p>For example:
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
<span class="k">if</span> <span class="n">a</span><span class="p">:</span>
<span class="k">return</span> <span class="n">x</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
<span class="k">return</span> <span class="n">y</span>
</pre></div>
<p>If the function returns at the first return, the file is never closed and the resource is leaked.
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
<span class="n">g</span><span class="p">(</span><span class="n">f</span><span class="p">)</span> <span class="c1"># Do something with f that may raise an exception.</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
<p>If the intervening code raises an exception, the function exits early and the file is never closed, so the resource is leaked.
</p><p>Both of these can be handled by a <code>try...finally</code> construct, which ensures that the finally clause is always executed on exit:
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="k">def</span> <span class="nf">func</span><span class="p">(</span><span class="n">filename</span><span class="p">):</span>
<span class="k">try</span><span class="p">:</span>
<span class="n">f</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">filename</span><span class="p">)</span>
<span class="c1"># Do something.</span>
<span class="k">finally</span><span class="p">:</span>
<span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
</pre></div>
<p>More generically:
</p>
<div class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><pre><span class="n">Resource</span><span class="w"> </span><span class="n">resource</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">getResource</span><span class="p">();</span>
<span class="k">try</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// Resource has been acquired; perform actions with the resource.</span>
<span class="w"> </span><span class="p">...</span>
<span class="p">}</span><span class="w"> </span><span class="k">finally</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// Release resource, even if an exception was thrown.</span>
<span class="w"> </span><span class="n">resource</span><span class="p">.</span><span class="n">dispose</span><span class="p">();</span>
<span class="p">}</span>
</pre></div>
<p>The <code>try...finally</code> construct is necessary for proper <a href="Exception_safety" title="Exception safety">exception safety</a>, since the <code>finally</code> block enables execution of cleanup logic regardless of if an exception is thrown or not in the <code>try</code> block.
</p><p>One disadvantage of this approach is that it requires the programmer to explicitly add cleanup code in a <code>finally</code> block. This leads to code size bloat, and failure to do so will lead to resource leakage in the program.
</p>
<div class="mw-heading mw-heading2"><h2 id="Language_constructs">Language constructs</h2></div>
<p>To make the safe use of the dispose pattern less verbose, several languages have some kind of built-in support for resources held and released in the same <a href="Block_(programming)" title="Block (programming)">block of code</a>.
</p><p>The <a href="C_Sharp_(programming_language)" title="C Sharp (programming language)">C#</a> language features the <code>using</code> statement<sup id="cite_ref-3" class="reference"><a href="#cite_note-3"><span class="cite-bracket">[</span>2<span class="cite-bracket">]</span></a></sup> that automatically calls the <code>Dispose</code> method on an object that implements the <code>IDisposable</code> <a href="Interface_(computer_science)" class="mw-redirect" title="Interface (computer science)">interface</a>:
</p>
<div class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><pre><span class="k">using</span><span class="w"> </span><span class="p">(</span><span class="n">Resource</span><span class="w"> </span><span class="n">resource</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">GetResource</span><span class="p">())</span>
<span class="p">{</span>
<span class="w"> </span><span class="c1">// Perform actions with the resource.</span>
<span class="w"> </span><span class="p">...</span>
<span class="p">}</span>
</pre></div>
<p>which is equal to:
</p>
<div class="mw-highlight mw-highlight-lang-csharp mw-content-ltr" dir="ltr"><pre><span class="n">Resource</span><span class="w"> </span><span class="n">resource</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="n">GetResource</span><span class="p">()</span>
<span class="k">try</span><span class="w"> </span>
<span class="p">{</span>
<span class="w"> </span><span class="c1">// Perform actions with the resource.</span>
<span class="w"> </span><span class="p">...</span>
<span class="p">}</span>
<span class="k">finally</span><span class="w"> </span>
<span class="p">{</span>
<span class="w"> </span><span class="c1">// Resource might not been acquired, or already freed</span>
<span class="w"> </span><span class="k">if</span><span class="w"> </span><span class="p">(</span><span class="n">resource</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="k">null</span><span class="p">)</span><span class="w"> </span>
<span class="w"> </span><span class="p">((</span><span class="n">IDisposable</span><span class="p">)</span><span class="n">resource</span><span class="p">).</span><span class="n">Dispose</span><span class="p">();</span><span class="w"> </span>
<span class="p">}</span>
</pre></div>
<p>Similarly, the <a href="Python_(programming_language)" title="Python (programming language)">Python</a> language has a <code>with</code> statement that can be used to similar effect with a <i>context manager</i> object. The <i>context manager protocol</i> requires implementing <code>__enter__</code> and <code>__exit__</code> methods which get automatically called by the <code>with</code> statement construct, to prevent duplication of code that would otherwise occur with the <code>try</code>/<code>finally</code> pattern.<sup id="cite_ref-4" class="reference"><a href="#cite_note-4"><span class="cite-bracket">[</span>3<span class="cite-bracket">]</span></a></sup>
</p>
<div class="mw-highlight mw-highlight-lang-python mw-content-ltr" dir="ltr"><pre><span class="k">with</span> <span class="n">resource_context_manager</span><span class="p">()</span> <span class="k">as</span> <span class="n">resource</span><span class="p">:</span>
<span class="c1"># Perform actions with the resource.</span>
<span class="o">...</span>
<span class="c1"># Perform other actions where the resource is guaranteed to be deallocated.</span>
<span class="o">...</span>
</pre></div>
<p>The <a href="Java_(programming_language)" title="Java (programming language)">Java</a> language introduced a new syntax called <code>try</code>-with-resources in Java version 7.<sup id="cite_ref-5" class="reference"><a href="#cite_note-5"><span class="cite-bracket">[</span>4<span class="cite-bracket">]</span></a></sup> It can be used on objects that implement the AutoCloseable interface (that defines method close()):
</p>
<div class="mw-highlight mw-highlight-lang-java mw-content-ltr" dir="ltr"><pre><span class="k">try</span><span class="w"> </span><span class="p">(</span><span class="n">OutputStream</span><span class="w"> </span><span class="n">x</span><span class="w"> </span><span class="o">=</span><span class="w"> </span><span class="k">new</span><span class="w"> </span><span class="n">OutputStream</span><span class="p">(...))</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// Do something with x</span>
<span class="p">}</span><span class="w"> </span><span class="k">catch</span><span class="w"> </span><span class="p">(</span><span class="n">IOException</span><span class="w"> </span><span class="n">ex</span><span class="p">)</span><span class="w"> </span><span class="p">{</span>
<span class="w"> </span><span class="c1">// Handle exception</span>

<span class="w"> </span><span class="c1">// The resource x is automatically closed</span>
<span class="p">}</span><span class="w"> </span><span class="c1">// try</span>
</pre></div>
<div class="mw-heading mw-heading2"><h2 id="Problems">Problems</h2></div>
<p>Beyond the key problem of correct resource management in the presence of returns and exceptions, and heap-based resource management (disposing objects in a different scope from where they are created), there are many further complexities associated with the dispose pattern. These problems are largely avoided by <a href="RAII" class="mw-redirect" title="RAII">RAII</a>. However, in common simple use these complexities do not arise: acquire a single resource, do something with it, automatically release it.
</p><p>A fundamental problem is that having a resource is no longer a <a href="Class_invariant" title="Class invariant">class invariant</a> (the resource is held from object creation until it is disposed, but the object is still live at this point), so the resource may not be available when the object tries to use it, for example trying to read from a closed file. This means that all methods on the object that use the resource potentially fail, concretely usually by returning an error or raising an exception. In practice this is minor, as use of resources can usually fail for other reasons as well (for example, trying to read past the end of a file), so these methods already might fail, and not having a resource just adds another possible failure. A standard way to implement this is to add a boolean field to the object, called <code>disposed</code>, which is set to true by <code>dispose</code>, and checked by a <a href="Guard_clause" class="mw-redirect" title="Guard clause">guard clause</a> to all methods (that use the resource), raising an exception (such as <code>ObjectDisposedException</code> in .NET) if the object has been disposed.<sup id="cite_ref-msdn_dispose_6-0" class="reference"><a href="#cite_note-msdn_dispose-6"><span class="cite-bracket">[</span>5<span class="cite-bracket">]</span></a></sup>
</p><p>Further, it is possible to call <code>dispose</code> on an object more than once. While this may indicate a programming error (each object holding a resource must be disposed <i>exactly</i> once), it is simpler, more robust, and thus usually preferable for <code>dispose</code> to be <a href="Idempotent" class="mw-redirect" title="Idempotent">idempotent</a> (meaning "calling multiple times is the same as calling once").<sup id="cite_ref-msdn_dispose_6-1" class="reference"><a href="#cite_note-msdn_dispose-6"><span class="cite-bracket">[</span>5<span class="cite-bracket">]</span></a></sup> This is easily implemented by using the same boolean <code>disposed</code> field and checking it in a guard clause at the start of <code>dispose</code>, in that case returning immediately, rather than raising an exception.<sup id="cite_ref-msdn_dispose_6-2" class="reference"><a href="#cite_note-msdn_dispose-6"><span class="cite-bracket">[</span>5<span class="cite-bracket">]</span></a></sup> Java distinguishes disposable types (those that implement <a rel="nofollow" class="external text" href="https://docs.oracle.com/javase/8/docs/api/java/lang/AutoCloseable.html">AutoCloseable</a>) from disposable types where dispose is idempotent (the subtype <a rel="nofollow" class="external text" href="https://docs.oracle.com/javase/8/docs/api/java/io/Closeable.html">Closeable</a>).
</p><p>Disposal in the presence of inheritance and composition of objects that hold resources have analogous problems to destruction/finalization (via destructors or finalizers). Further, since the dispose pattern usually does not have language support for this, <a href="Boilerplate_code" title="Boilerplate code">boilerplate code</a> is necessary. Firstly, if a derived class overrides a <code>dispose</code> method in the base class, the overriding method in the derived class generally needs to call the <code>dispose</code> method in the base class, in order to properly release resources held in the base. Secondly, if an object has a "has a" relationship with another object that holds a resource (i.e., if an object indirectly uses a resource through another object that directly uses a resource), should the indirectly using object be disposable? This corresponds to whether the relationship is <i>owning</i> (<a href="Object_composition" title="Object composition">object composition</a>) or <i>viewing</i> (<a href="Object_aggregation" class="mw-redirect" title="Object aggregation">object aggregation</a>), or even just <i>communicating</i> (<a href="Association_(object-oriented_programming)" title="Association (object-oriented programming)">association</a>), and both conventions are found (indirect user is responsible for the resource or is not responsible). If the indirect use is responsible for the resource, it must be disposable, and dispose the owned objects when it is disposed (analogous to destroying or finalizing owned objects).
</p><p>Composition (owning) provides <a href="Encapsulation_(computer_programming)" title="Encapsulation (computer programming)">encapsulation</a> (only the object that is used needs to be tracked), but at the cost of considerable complexity when there are further relationships between objects, while aggregation (viewing) is considerably simpler, at the cost of lacking encapsulation. In <a href=".NET_Framework" title=".NET Framework">.NET</a>, convention is to only have direct user of resources be responsible: "You should implement IDisposable only if your type uses unmanaged resources directly."<sup id="cite_ref-idisposable_7-0" class="reference"><a href="#cite_note-idisposable-7"><span class="cite-bracket">[</span>6<span class="cite-bracket">]</span></a></sup> See <a href="Resource_management_(computing)" title="Resource management (computing)">resource management</a> for details, and further examples.
</p>
<div class="mw-heading mw-heading2"><h2 id="See_also">See also</h2></div>
<ul><li><a href="Object_lifetime" title="Object lifetime">Object lifetime</a></li>
<li><a href="Resource_Acquisition_Is_Initialization" class="mw-redirect" title="Resource Acquisition Is Initialization">Resource Acquisition Is Initialization</a> (RAII)</li></ul>
<div class="mw-heading mw-heading2"><h2 id="Notes">Notes</h2></div>
<style data-mw-deduplicate="TemplateStyles:r1239543626">
/* start https://en.wikipedia.org/ */


.mw-parser-output .reflist{margin-bottom:0.5em;list-style-type:decimal}@media screen{.mw-parser-output .reflist{font-size:90%}}.mw-parser-output .reflist .references{font-size:100%;margin-bottom:0;list-style-type:inherit}.mw-parser-output .reflist-columns-2{column-width:30em}.mw-parser-output .reflist-columns-3{column-width:25em}.mw-parser-output .reflist-columns{margin-top:0.3em}.mw-parser-output .reflist-columns ol{margin-top:0}.mw-parser-output .reflist-columns li{page-break-inside:avoid;break-inside:avoid-column}.mw-parser-output .reflist-upper-alpha{list-style-type:upper-alpha}.mw-parser-output .reflist-upper-roman{list-style-type:upper-roman}.mw-parser-output .reflist-lower-alpha{list-style-type:lower-alpha}.mw-parser-output .reflist-lower-greek{list-style-type:lower-greek}.mw-parser-output .reflist-lower-roman{list-style-type:lower-roman}


/* end https://en.wikipedia.org/ */
</style><div class="reflist reflist-lower-alpha">
<div class="mw-references-wrap"><ol class="references">
<li id="cite_note-2"><span class="mw-cite-backlink"><b><a href="#cite_ref-2">^</a></b></span> <span class="reference-text">In <a href="Class-based_programming" title="Class-based programming">class-based programming</a>, methods are defined in a class, using an implicit <code>this</code> or <code>self</code> parameter, rather than as functions taking an explicit parameter.</span>
</li>
</ol></div></div>
<div class="mw-heading mw-heading2"><h2 id="References">References</h2></div>
<div class="reflist">
<div class="mw-references-wrap"><ol class="references">
<li id="cite_note-1"><span class="mw-cite-backlink"><b><a href="#cite_ref-1">^</a></b></span> <span class="reference-text"><span class="neverexpand"><code><a rel="nofollow" class="external text" href="https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/stdio.h.html">stdio.h</a></code></span>&nbsp;–&nbsp;Base Definitions Reference, <a href="Single_Unix_Specification" class="mw-redirect" title="Single Unix Specification">The Single UNIX Specification</a>, Version 5 from <a href="The_Open_Group" title="The Open Group">The Open Group</a></span>
</li>
<li id="cite_note-3"><span class="mw-cite-backlink"><b><a href="#cite_ref-3">^</a></b></span> <span class="reference-text">Microsoft MSDN: <a rel="nofollow" class="external text" href="http://msdn.microsoft.com/en-us/library/yh598w02.aspx">using Statement (C# Reference)</a></span>
</li>
<li id="cite_note-4"><span class="mw-cite-backlink"><b><a href="#cite_ref-4">^</a></b></span> <span class="reference-text"><style data-mw-deduplicate="TemplateStyles:r1238218222">
/* start https://en.wikipedia.org/ */


.mw-parser-output cite.citation{font-style:inherit;word-wrap:break-word}.mw-parser-output .citation q{quotes:"\"""\"""'""'"}.mw-parser-output .citation:target{background-color:rgba(0,127,255,0.133)}.mw-parser-output .id-lock-free.id-lock-free a{background:url("./mw/Lock-green.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-limited.id-lock-limited a,.mw-parser-output .id-lock-registration.id-lock-registration a{background:url("./mw/Lock-gray-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .id-lock-subscription.id-lock-subscription a{background:url("./mw/Lock-red-alt-2.svg")right 0.1em center/9px no-repeat}.mw-parser-output .cs1-ws-icon a{background:url("./mw/Wikisource-logo.svg")right 0.1em center/12px no-repeat}body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-free a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-limited a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-registration a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .id-lock-subscription a,body:not(.skin-timeless):not(.skin-minerva) .mw-parser-output .cs1-ws-icon a{background-size:contain;padding:0 1em 0 0}.mw-parser-output .cs1-code{color:inherit;background:inherit;border:none;padding:inherit}.mw-parser-output .cs1-hidden-error{display:none;color:var(--color-error,#d33)}.mw-parser-output .cs1-visible-error{color:var(--color-error,#d33)}.mw-parser-output .cs1-maint{display:none;color:#085;margin-left:0.3em}.mw-parser-output .cs1-kern-left{padding-left:0.2em}.mw-parser-output .cs1-kern-right{padding-right:0.2em}.mw-parser-output .citation .mw-selflink{font-weight:inherit}@media screen{.mw-parser-output .cs1-format{font-size:95%}html.skin-theme-clientpref-night .mw-parser-output .cs1-maint{color:#18911f}}@media screen and (prefers-color-scheme:dark){html.skin-theme-clientpref-os .mw-parser-output .cs1-maint{color:#18911f}}


/* end https://en.wikipedia.org/ */
</style><cite id="CITEREFGuido_van_Rossum,_Nick_Coghlan2011" class="citation web cs1"><a href="Guido_van_Rossum" title="Guido van Rossum">Guido van Rossum</a>, Nick Coghlan (13 June 2011). <a rel="nofollow" class="external text" href="http://legacy.python.org/dev/peps/pep-0343/">"PEP 343: The "with" Statement"</a>. Python Software Foundation.</cite></span>
</li>
<li id="cite_note-5"><span class="mw-cite-backlink"><b><a href="#cite_ref-5">^</a></b></span> <span class="reference-text">Oracle Java tutorial: <a rel="nofollow" class="external text" href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html">The try-with-resources Statement</a></span>
</li>
<li id="cite_note-msdn_dispose-6"><span class="mw-cite-backlink">^ <a href="#cite_ref-msdn_dispose_6-0"><sup><i><b>a</b></i></sup></a> <a href="#cite_ref-msdn_dispose_6-1"><sup><i><b>b</b></i></sup></a> <a href="#cite_ref-msdn_dispose_6-2"><sup><i><b>c</b></i></sup></a></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx">"Dispose Pattern"</a>.</cite></span>
</li>
<li id="cite_note-idisposable-7"><span class="mw-cite-backlink"><b><a href="#cite_ref-idisposable_7-0">^</a></b></span> <span class="reference-text"><cite class="citation web cs1"><a rel="nofollow" class="external text" href="https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-idisposable#implement-idisposable">"IDisposable Interface"</a><span class="reference-accessdate">. Retrieved <span class="nowrap">2024-12-09</span></span>.</cite></span>
</li>
</ol></div></div>
<div class="mw-heading mw-heading2"><h2 id="Further_reading">Further reading</h2></div>
<ul><li>Microsoft Developer Network: <a rel="nofollow" class="external text" href="https://msdn.microsoft.com/en-us/library/b1yfkh5e(v=vs.110).aspx">Dispose Pattern</a></li></ul></div><!--htdig_noindex--><div><div class="zim-footer">
This article is issued from <a class="external text" title="Last edited on 2025-01-05" href="https://en.wikipedia.org/wiki/?title=Dispose_pattern&amp;oldid=1267558034">Wikipedia</a>. The text is available under <a class="external text" href="https://creativecommons.org/licenses/by-sa/4.0/deed.en">Creative Commons Attribution-Share Alike 4.0</a> unless otherwise noted. Additional terms may apply for the media files.
</div>
</div><!--/htdig_noindex--></div>
</div>
</main>
</div>
</div>
</div>

</body></html>